package com.internetCafes.spms.web.customer.service.impl.area;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.core.exception.RRException;
import com.internetCafes.spms.core.exception.RRExceptionCodeEnum;
import com.internetCafes.spms.web.customer.common.cont.AreaConst;
import com.internetCafes.spms.web.customer.common.cont.CommonConst;
import com.internetCafes.spms.web.customer.common.util.UserInfoUtil;
import com.internetCafes.spms.web.customer.entity.area.AreaManager;
import com.internetCafes.spms.web.customer.entity.area.AreaSale;
import com.internetCafes.spms.web.customer.mapper.area.AreaSaleMapper;
import com.internetCafes.spms.web.customer.model.area.EntAreaSaleDo;
import com.internetCafes.spms.web.customer.model.area.EntAreaSalePo;
import com.internetCafes.spms.web.customer.model.area.EntAreaUserConfigReq;
import com.internetCafes.spms.web.customer.service.area.IAreaManagerService;
import com.internetCafes.spms.web.customer.service.area.IAreaSaleService;
import com.internetCafes.spms.web.sys.model.UserInfo;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import com.sms.common.util.hutool.core.date.DateTime;
import com.sms.common.util.hutool.core.date.DateUtil;
import com.sms.common.util.hutool.core.util.ObjectUtil;
import com.sms.common.util.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 区域负责人表 服务实现类
 * </p>
 *
 * @author Zj
 * @since 2021-10-18
 */
@Service
public class AreaSaleServiceImpl extends ServiceImpl<AreaSaleMapper, AreaSale> implements IAreaSaleService {

    @Autowired
    private IAreaManagerService managerService;

    @Override
    public List<EntAreaSalePo> listPo(EntAreaSaleDo entAreaSaleDo) {
        return baseMapper.listPo(entAreaSaleDo);
    }

    @Override
    public boolean deleteConfig(EntAreaUserConfigReq req) {
        UserInfo userEntity = ShiroUtils.getUserEntity();

        if (!UserInfoUtil.entSuperAdminJudge(userEntity)) {
            // 查看当前用户是否支持分配
            List<AreaManager> managerList = managerService.list(new LambdaQueryWrapper<AreaManager>()
                    .and(eq -> eq.in(AreaManager::getAreaId, req.getAreaIdList())
                            .or()
                            .in(AreaManager::getCityId, req.getCityId()))
                    .eq(AreaManager::getEffectiveFlag, CommonConst.FlagEnum.IS.getId())
                    .eq(AreaManager::getManagerId, userEntity.getId())
                    .orderByDesc(AreaManager::getId));

            List<Long> areaIdList = managerList.stream()
                    .map(AreaManager::getAreaId)
                    .collect(Collectors.toList());

            if (!areaIdList.contains(req.getCityId())) {
                List<Long> noManagerAreaIdList = req.getAreaIdList()
                        .stream()
                        .filter(areaReqId -> !areaIdList.contains(areaReqId))
                        .collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(noManagerAreaIdList)) {
                    throw new RRException(RRExceptionCodeEnum.NO_AUTHORITY);
                }
            }

        }
        LambdaUpdateWrapper<AreaSale> updateWrapper = new LambdaUpdateWrapper<AreaSale>()
                .in(AreaSale::getAreaId, req.getAreaIdList())
                .eq(AreaSale::getEffectiveFlag, CommonConst.FlagEnum.IS.getId())
                .set(AreaSale::getEffectiveFlag, CommonConst.FlagEnum.NOT.getId());
        return update(updateWrapper);
    }

    @Override
    public boolean config(EntAreaUserConfigReq req) {

        if (ObjectUtil.isNull(req.getCityId()) || CollectionUtil.isEmpty(req.getUserIdList())
                || ObjectUtil.isNull(req.getAreaId())
                || ObjectUtil.isNull(req.getTypeId()) || ObjectUtil.isNull(req.getAlwaysFlag())
                || !AreaConst.AreaUserConfigTypeEnum.getTypeIdList().contains(req.getTypeId())) {
            throw new RRException(RRExceptionCodeEnum.PARAM_ERROR);
        }
        if (CommonConst.FlagEnum.NOT.getId().equals(req.getAlwaysFlag())) {
            if (StrUtil.isBlank(req.getEndTime())) {
                throw new RRException(RRExceptionCodeEnum.PARAM_ERROR);
            }
        }

        UserInfo userEntity = ShiroUtils.getUserEntity();

        DateTime endTime = null;

        if (StrUtil.isNotBlank(req.getEndTime())) {
            endTime = DateUtil.parseDate(req.getEndTime());
        }
        if (!UserInfoUtil.entSuperAdminJudge(userEntity)) {
            // 查看当前用户是否支持分配
            List<AreaManager> managerList = managerService.list(new LambdaQueryWrapper<AreaManager>()
                .eq(AreaManager::getAreaId, req.getAreaId())
                .eq(AreaManager::getEffectiveFlag, CommonConst.FlagEnum.IS.getId())
                .eq(AreaManager::getManagerId, userEntity.getId())
                .orderByDesc(AreaManager::getId));

            if (CollectionUtil.isEmpty(managerList) ) {
                throw new RRException(RRExceptionCodeEnum.NO_AUTHORITY);
            }

            // 判断是否是永久有效管理员
            AreaManager managerInfo = CollectionUtil.getFirst(managerList);


            if (CommonConst.FlagEnum.NOT.getId().equals(req.getAlwaysFlag())) {
                if (StrUtil.isBlank(req.getEndTime())) {
                    throw new RRException(RRExceptionCodeEnum.PARAM_ERROR);
                }
                if (CommonConst.FlagEnum.NOT.getId().equals(managerInfo.getAlwaysFlag())) {
                    assert endTime != null;
                    if (endTime.isAfter(CollectionUtil.getFirst(managerList).getEndTime())) {
                        throw new RRException(RRExceptionCodeEnum.CUSTOMER_SALE_TOO_LONG);
                    }
                }
            } else {
                if (CommonConst.FlagEnum.NOT.getId().equals(managerInfo.getAlwaysFlag())) {
                    throw new RRException(RRExceptionCodeEnum.CUSTOMER_SALE_TOO_LONG);
                }
            }
        }

        // 负责人 获取已经分配的数据
        LambdaUpdateWrapper<AreaSale> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AreaSale::getAreaId, req.getAreaId())
                .eq(AreaSale::getEffectiveFlag, CommonConst.FlagEnum.IS.getId())
                .set(AreaSale::getEffectiveFlag, CommonConst.FlagEnum.NOT.getId());

        update(updateWrapper);

        DateTime now = DateTime.now();
        DateTime finalEndTime = endTime;
        List<AreaSale> batchDo = req.getUserIdList()
                .stream()
                .map(userId ->
                        new AreaSale().setCityId(req.getCityId()).setAreaId(req.getAreaId()).setStartTime(now)
                                .setEndTime(finalEndTime).setEffectiveFlag(CommonConst.FlagEnum.IS.getId())
                                .setSaleId(userId).setAlwaysFlag(req.getAlwaysFlag())
                ).collect(Collectors.toList());

        // 新增
        return saveBatch(batchDo);
    }

    @Override
    public void updateExpiredSale() {
        baseMapper.updateExpiredSale();
    }
}
